//
//  SendPostsController.swift
//  maopu
//
//  Created by 黄海波 on 2017/4/25.
//  Copyright © 2017年 maopu. All rights reserved.
// 发送图文贴页面

import UIKit

class SendPostsController: BaseViewController , UITextViewDelegate , UITextFieldDelegate{
    fileprivate var scrollerView:UIScrollView!
    fileprivate var topView:UIView!
    fileprivate var sectionBtn:UIButton!
    fileprivate var titleTF:UITextField!
    fileprivate var titleCountLab:UILabel!
    fileprivate var titleCount = 26
    
    fileprivate var textView:UITextView!
    fileprivate var textHintLab:UILabel!
    fileprivate var textCountLab:UILabel!
    fileprivate var textCount = 5000
    
    fileprivate var chooseImagesView:ChooseImagesView!
    
    fileprivate var bottomView:PostsToolView!
    
    fileprivate var keyBoardHeight:CGFloat = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.initView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillChangeFrame(_:)), name:NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    func keyBoardWillShow(_ note:Notification){
        KeyBoardUtils.shared.keyBoardWillShow(note, showView: self.bottomView) { (keyBoardHeight) in
            
        }
    }
    
    func keyBoardWillHide(_ note:Notification){
        KeyBoardUtils.shared.keyBoardWillHide(note, hideView: self.bottomView) {
            self.scrollerView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)
        }
    }
    
    func keyBoardWillChangeFrame(_ note:Notification){
        KeyBoardUtils.shared.keyBoardWillChangeFrame(note) { (keyBoardHeight) in
            Log.shared.printLog("键盘高度:  \(keyBoardHeight)")
            self.keyBoardHeight = keyBoardHeight
            self.updateTextViewFrame()
//            if self.textView.isFirstResponder{
//                
//            }
        }
    }
    
    
    fileprivate func initView(){
        self.navigationItem.title = "发帖"
        self.view.backgroundColor = UIColor.white
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.setTextBarButton("发布", action: #selector(self.senPostsClick), target: self)
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.scrollerView = UIScrollView.init(frame: CGRect.init(x: 0, y: NavigationH, width: AppWidth, height: AppHeight - NavigationH - 60))
        self.scrollerView.backgroundColor = UIColor.white
        self.scrollerView.keyboardDismissMode = .onDrag
        self.scrollerView.alwaysBounceVertical = true
        self.view.addSubview(self.scrollerView)
        
        let releaseHintLab = UILabel.init(frame: CGRect.init(x: 21, y: 20, width: 40, height: 17))
        releaseHintLab.font = UIFont.LightDefaultFont(12)
        releaseHintLab.text = "发布于"
        releaseHintLab.textColor = UIColor.m_102Color()
        self.scrollerView.addSubview(releaseHintLab)
        
        self.sectionBtn = UIButton.init(type: .custom)
        self.sectionBtn.frame = CGRect.init(x: releaseHintLab.frame.maxX + 15 , y: 13.5, width: AppWidth - releaseHintLab.frame.maxX - 15 - 20 - 7 - 15 , height: 30)
        self.sectionBtn.setTitleColor(UIColor.m_102Color(), for: UIControlState.normal)
        self.sectionBtn.setTitle("请选择板块", for: UIControlState.normal)
        self.sectionBtn.contentHorizontalAlignment = .right
        self.sectionBtn.titleLabel?.font = UIFont.LightDefaultFont(12)
        self.scrollerView.addSubview(self.sectionBtn)
        
        let nextImg = UIImageView.init(frame: CGRect.init(x: AppWidth - 20 - 12, y: 23, width: 7, height: 12))
        nextImg.image = UIImage.init(named: "next_ico")
        self.scrollerView.addSubview(nextImg)
        
        let lineView_one = UIView.init(frame: CGRect.init(x: 20, y: releaseHintLab.frame.maxY + 20, width: AppWidth - 20, height: 1))
        lineView_one.backgroundColor = UIColor.m_lineColor()
        self.scrollerView.addSubview(lineView_one)
        
        self.titleTF = UITextField.init(frame: CGRect.init(x: 20, y: lineView_one.frame.maxY + 15, width: AppWidth - 20 - 60, height: 30))
        self.titleTF.borderStyle = .none
        self.titleTF.autocorrectionType = .no
        self.titleTF.becomeFirstResponder()
        self.titleTF.placeholder = "请输入标题(5~26个字)"
        self.titleTF.delegate = self
        self.titleTF.textColor = UIColor.m_textDeepColor()
        self.titleTF.font = UIFont.RegularDefaultFont(15)
        self.titleTF.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
        self.scrollerView.addSubview(self.titleTF)
        
        self.titleCountLab = UILabel.init(frame: CGRect.init(x: AppWidth - 50 - 20, y: lineView_one.frame.maxY + 21.5, width: 50, height: 17))
        titleCountLab.font = UIFont.LightDefaultFont(12)
        titleCountLab.text = "26"
        titleCountLab.textAlignment = .right
        titleCountLab.textColor = UIColor.m_170Color()
        self.scrollerView.addSubview(titleCountLab)
        
        let lineView_two = UIView.init(frame: CGRect.init(x: 20, y: self.titleTF.frame.maxY + 15, width: AppWidth - 20, height: 1))
        lineView_two.backgroundColor = UIColor.m_lineColor()
        self.scrollerView.addSubview(lineView_two)
        
        self.textView = UITextView.init(frame: CGRect.init(x: 20, y: lineView_two.frame.maxY + 10, width: AppWidth - 40, height: 100))
        self.textView.autocorrectionType = .no
        self.textView.font = UIFont.RegularDefaultFont(15)
        self.textView.textColor = UIColor.m_textDeepColor()
        self.textView.delegate = self
        self.textView.isScrollEnabled = false
        self.textView.layoutManager.allowsNonContiguousLayout = false
        self.scrollerView.addSubview(self.textView)
        
        self.textHintLab = UILabel.init(frame: CGRect.init(x: 5, y: 7, width: 260, height: 20))
        self.textHintLab.font = UIFont.LightDefaultFont(15)
        self.textHintLab.textColor = UIColor.m_placeholderColor()
        self.textHintLab.text = "请输入内容（可选，最多5,000字）"
        self.textView.addSubview(self.textHintLab)
        
        let imgWidth = Util.shared.getImgWidthForCollectionView(itemSpacing: 5, maxWidth: AppWidth - 40, rowCount: 4)
        self.chooseImagesView = ChooseImagesView.init(scrollDirection: .horizontal, frame: CGRect.init(x: 20, y: self.textView.frame.maxY + 10, width: AppWidth - 40, height: 0) , cellWidth:imgWidth)
        self.chooseImagesView.backgroundColor = UIColor.white
        self.scrollerView.addSubview(self.chooseImagesView)
        
        self.scrollerView.contentSize = CGSize.init(width: AppWidth, height: self.chooseImagesView.frame.maxY + 20)
        
        self.bottomView = PostsToolView.init(isShowVideo: true, frame: CGRect(x: 0, y: AppHeight - 50, width: AppWidth, height: 50))
        self.view.addSubview(self.bottomView)
        
        self.textCountLab = UILabel.init(frame: CGRect.init(x: AppWidth - 100 - 20, y: 16.5, width: 100, height: 17))
        textCountLab.font = UIFont.LightDefaultFont(12)
        textCountLab.text = "\(self.textCount)"
        textCountLab.textAlignment = .right
        textCountLab.textColor = UIColor.m_170Color()
        self.bottomView.addSubview(textCountLab)
    }
    
    @objc fileprivate func senPostsClick(){
        
    }
    
    func textViewDidChange(_ textView: UITextView) {
        if(textView.text.characters.count > 0){
            self.textHintLab.isHidden = true
        }else{
            self.textHintLab.isHidden = false
        }
        self.updateTextViewFrame()
        
        let selectedRange = textView.markedTextRange  //获取高亮部分
        var pos:UITextPosition?
        if selectedRange != nil{
            pos = textView.position(from: selectedRange!.start, offset: 0)
        }
        if selectedRange != nil && pos != nil{  //如果在变化中是高亮部分在变，就不要计算字符了
            return
        }
        
        if textView.text!.characters.count >= self.textCount{
            textView.text = textView.text!.substring(to: textView.text!.index(textView.text!.startIndex, offsetBy: self.textCount))
        }
        if textView.text != ""{
            if textView.text!.characters.count >= self.textCount{
                self.textCountLab.text = "0"
            }else{
                let count = self.textCount - textView.text!.characters.count
                self.textCountLab.text = "\(count)"
            }
        }else{
            self.textCountLab.text = "\(self.textCount)"
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    func textFieldDidChange(_ textField: UITextField){
        let selectedRange = textField.markedTextRange  //获取高亮部分
        var pos:UITextPosition?
        if selectedRange != nil{
            pos = textField.position(from: selectedRange!.start, offset: 0)
        }
        if selectedRange != nil && pos != nil{  //如果在变化中是高亮部分在变，就不要计算字符了
            return
        }
        
        if textField.text!.characters.count >= 26{
            textField.text = textField.text!.substring(to: textField.text!.index(textField.text!.startIndex, offsetBy: 26))
        }
        
        if textField.text != ""{
            if textField.text!.characters.count >= 26{
                self.titleCountLab.text = "0"
            }else{
                let count = 26 - textField.text!.characters.count
                self.titleCountLab.text = "\(count)"
            }
        }else{
            self.titleCountLab.text = "26"
        }
    }
    
    fileprivate func updateTextViewFrame(){
        let height = StringSizeEngine.calculateStringHeight(textView.text, width: AppWidth - 50 , font: textView.font!)
        
        if height > 80.0{
            UIView.animate(withDuration: 0.3, animations: {
                self.textView.frame = CGRect.init(x: self.textView.frame.minX, y: self.textView.frame.minY, width: self.textView.frame.size.width, height: height + 10)
            })
        }else{
            UIView.animate(withDuration: 0.3, animations: {
                self.textView.frame = CGRect.init(x: 20, y: self.titleTF.frame.maxY + 26, width: AppWidth - 40, height: 100)
            })
        }
        UIView.animate(withDuration: 0.3) {
            self.chooseImagesView.frame = CGRect.init(x: 20, y: self.textView.frame.maxY + 10, width: AppWidth - 40, height: self.chooseImagesView.frame.size.height)
            self.scrollerView.contentSize = CGSize.init(width: AppWidth, height: self.chooseImagesView.frame.maxY + 20)
            if self.textView.frame.maxY > self.keyBoardHeight  && height > 80{
                self.scrollerView.setContentOffset(CGPoint.init(x: 0, y: (self.textView.frame.maxY - self.keyBoardHeight)), animated: false)
            }else{
                self.scrollerView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: false)
            }
        }
    }

}
